<template>
    <div>
      <h2 style="float:  left">采购订单列表</h2>
      <div style="float: right">
        <el-button type="primary"  @click="openOrderDialog">新增采购订单</el-button>
        <el-button type="info"  @click="logout">退出登录</el-button>
      </div>

      <el-table
          :data="tableData"
          border
          style="width: 100%">
        <el-table-column
            type="index"
            label="序号">
        </el-table-column>
        <el-table-column
            prop="orderCode"
            label="订单编码">
        </el-table-column>
        <el-table-column
            prop="name"
            label="订单名称">
        </el-table-column>
        <el-table-column
            prop="typeName"
            label="订单类型">
        </el-table-column>
        <el-table-column
            prop="projectName"
            label="所属项目">
        </el-table-column>
        <el-table-column
            prop="companyName"
            label="供应商">
        </el-table-column>
        <el-table-column
            prop="signDate"
            label="签订日期">
        </el-table-column>
        <el-table-column
            prop="username"
            label="采购员">
        </el-table-column>
        <el-table-column
            prop="deptName"
            label="采购部门">
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间">
        </el-table-column>
        <el-table-column
            prop="status"
            label="审批状态">
          <template slot-scope="scope">
            {{statusMap[scope.row.status]}}
          </template>
        </el-table-column>
        <el-table-column
            label="操作">
          <template slot-scope="scope">
            <el-button type="info" v-if="scope.row.status == 1 && dept==1">撤回</el-button><br>
            <el-button type="success" v-if="scope.row.status == 0" @click="doSubmitApprove(scope.row.id)">提交</el-button><br>
            <el-button type="primary" v-if="(scope.row.status == 3 || scope.row.status ==0) && dept==1" @click="edit(scope.row.id)">修改</el-button><br>
            <el-button type="primary" v-if="scope.row.status == 1 && dept==2" @click="edit(scope.row.id)">审批</el-button><br>
          </template>
        </el-table-column>
      </el-table>


      <el-dialog
          title="新建采购订单"
          :visible.sync="orderDialog"
          width="70%">

        <el-steps :active="active" finish-status="success">
          <el-step title="完善采购订单头信息"></el-step>
          <el-step title="完善采购订单行信息"></el-step>
        </el-steps>

        <div v-if="active==0">
          <el-form ref="form" :model="form" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="订单编码">
                  <el-input v-model="form.order.orderCode" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="订单名称">
                  <el-input v-model="form.order.name"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="订单类型">
                  <el-select v-model="form.order.typeId" placeholder="请选择订单类型">
                    <el-option
                        v-for="type in typeArray"
                        :key="type.id"
                        :label="type.name"
                        :value="type.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属项目">
                  <el-select v-model="form.order.projectId" placeholder="请选择订单类型">
                    <el-option
                        v-for="project in projectArray"
                        :key="project.id"
                        :label="project.name"
                        :value="project.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="订单备注">
                  <el-input type="textarea" v-model="form.order.content"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="供应商">
                  <el-select v-model="form.order.companyId" placeholder="请选择订单类型">
                    <el-option
                        v-for="company in companyArray"
                        :key="company.id"
                        :label="company.name"
                        :value="company.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="订单金额">
                  <el-input v-model="form.order.sumPrice" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="币种">
                  <el-select v-model="form.order.moneyType" placeholder="请选择币种类型">
                    <el-option
                        v-for="money in moneyArray"
                        :key="money.id"
                        :label="money.name"
                        :value="money.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预付款金额">
                  <el-input v-model="form.order.prePrice"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="订单开始时间">
                  <el-date-picker
                      v-model="form.order.startDate"
                      type="date"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择订单开始时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="订单结束时间">
                  <el-date-picker
                      v-model="form.order.endDate"
                      type="date"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择订单结束时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="签订时间">
                  <el-date-picker
                      v-model="form.order.signDate"
                      type="date"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择签订时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="计税类型">
                  <el-select v-model="form.order.taxType" placeholder="请选择计税类型">
                    <el-option
                        v-for="tax in taxArray"
                        :key="tax.id"
                        :label="tax.name"
                        :value="tax.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="税率">
                  <el-input v-model="form.order.taxValue"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="采购员">
                  <el-input v-model="username" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="附件">
                  <el-upload
                      class="upload-demo"
                      drag
                      action="/api/purchase/upload"
                      multiple
                      :on-success="handleAvatarSuccess"
                      :headers="{'token':token}"
                      :on-remove="handleRemove">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <div v-if="active==1">
          <el-button type="primary" @click="orderDetailVisible=true">新增订单行</el-button>

          <el-table
              :data="orderDetailData"
              border
              style="width: 100%">
            <el-table-column
                prop="goodsId"
                label="物料名称">
              <template slot-scope="scope">
                {{goodsMap[scope.row.goodsId]}}
              </template>
            </el-table-column>
            <el-table-column
                prop="price"
                label="单价">
            </el-table-column>
            <el-table-column
                prop="count"
                label="数量">
            </el-table-column>
            <el-table-column
                prop="unit"
                label="单位">
              <template slot-scope="scope">
                {{unitMap[scope.row.unit]}}
              </template>
            </el-table-column>
            <el-table-column
                prop="subtotalPrice"
                label="行金额">
            </el-table-column>
            <el-table-column
                prop="content"
                label="行摘要">
            </el-table-column>
            <el-table-column
                label="操作">
              <template slot-scope="scope">
                <el-button type="danger" @click="removeOrderDetail(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="orderDialog = false">取 消</el-button>
          <el-button v-if="active!=0" type="primary" style="margin-top: 12px;" @click="prev">上一步</el-button>
          <el-button v-if="active!=1" type="primary" style="margin-top: 12px;" @click="next">下一步</el-button>
          <el-button v-if="active==1 && dept==1" type="primary" @click="submitForm(0)">保   存</el-button>
          <el-button v-if="active==1 && dept==1" type="primary" @click="submitForm(1)">提交审批</el-button>
          <el-button type="success" v-if="active==1 && dept==2" @click="approve(2)">通  过</el-button>
          <el-button type="danger" v-if="active==1 && dept==2" @click="approve(3)">驳  回</el-button>
        </span>

        <hr>
        {{goodsMap}}
      </el-dialog>

      <el-dialog
          title="新增订单行"
          :visible.sync="orderDetailVisible"
          width="40%">

        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="物料">
            <el-cascader
                v-model="goodsValue"
                :options="goodsArray"
                :props="{'label':'name','value':'id'}"></el-cascader>
          </el-form-item>
          <el-form-item label="单价">
            <el-input v-model="tempOrderDetail.price"></el-input>
          </el-form-item>
          <el-form-item label="数量">
            <el-input v-model="tempOrderDetail.count"></el-input>
          </el-form-item>
          <el-form-item label="单位">
            <el-select v-model="tempOrderDetail.unit" placeholder="请选择">
              <el-option
                  v-for="unit in unitArray"
                  :key="unit.id"
                  :label="unit.name"
                  :value="unit.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="行金额">
            <el-input v-model="tempOrderDetail.subtotalPrice" disabled></el-input>
          </el-form-item>
          <el-form-item label="行摘要">
            <el-input type="textarea" v-model="tempOrderDetail.content"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="orderDetailVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitOrderDetail">确 定</el-button>
        </span>
      </el-dialog>

    </div>
</template>

<script>
import { goodsList, companyList, projectList, typeList, initForm, goodsListAll, submitForm, list, submitApprove, edit, approve } from '@/api/purchaseApi'
export default {
  data() {
    return {
      token:'',
      username:'',
      tableData: [],
      orderDetailData:[],
      orderDialog: false,
      orderDetailVisible: false,
      active: 0,
      form:{
        order:{
          filePath:''
        },
        orderDetailList:[]
      },
      goodsArray:[],
      companyArray:[],
      projectArray:[],
      typeArray:[],
      moneyArray:[
        {
          id:'1',
          name:'人民币'
        },
        {
          id:'2',
          name:'美元'
        }
      ],
      taxArray:[
        {
          id:'1',
          name:'增值税'
        },
        {
          id:'2',
          name:'附加税'
        }
      ],
      unitArray:[
        {
          id:'1',
          name:'吨'
        },
        {
          id:'2',
          name:'立方米'
        },
        {
          id:'3',
          name:'件'
        }
      ],
      unitMap:{
        1:'吨',
        2:'立方米',
        3:'件'
      },
      fileArray:[],
      tempOrderDetail:{

      },
      goodsValue:[],
      goodsMap:{

      },
      statusMap:{
        0:'待提交',
        1:'待审批',
        2:'审批通过',
        3:'审批驳回'
      },
      dept: null
    }
  },
  watch:{
    'tempOrderDetail.price':function (newVal, oldVal){
      if(newVal == undefined){
        return;
      }


      var reg = /^\d+$/
      if(!reg.test(newVal)){
        this.$message.warning("请输入数值类型!")
        this.tempOrderDetail.price = 0;
      }


      var count = 0;
      if(this.tempOrderDetail.count != undefined){
        count =  this.tempOrderDetail.count;
      }

      this.tempOrderDetail.subtotalPrice = count * newVal
    },
    'tempOrderDetail.count':function (newVal, oldVal){

      if(newVal == undefined){
        return;
      }

      var reg = /^\d+$/
      if(!reg.test(newVal)){
        this.$message.warning("请输入数值类型!")
        this.tempOrderDetail.count = 0;
      }

      var price = 0;
      if(this.tempOrderDetail.price != undefined){
        price =  this.tempOrderDetail.price;
      }

      this.tempOrderDetail.subtotalPrice = price * newVal
    },
    'orderDetailData': function (newValue, oldVal){
      var sumprice = 0;
      for(var i in newValue){
        var detail = newValue[i]
        sumprice += detail.subtotalPrice
      }
      this.form.order.sumPrice = sumprice
    }
  },
  methods:{
    openOrderDialog(){
      initForm().then((res)=>{
        if(res.success){
          this.form.order.orderCode = res.data.orderId
          this.form.order.userId = res.data.id
          this.username = res.data.username
        }
      })


      this.orderDialog = true
    },
    prev() {
      this.active--
    },
    next() {
      this.active++
    },
    queryGoods(){
      goodsList().then((res)=>{
        if(res.success){
          this.goodsArray = res.data;
        }
      })

      goodsListAll().then((res)=>{
        if(res.success){
          for(var i in res.data){
            var goods = res.data[i];
            this.goodsMap[goods.id] = goods.name
          }
        }
      })

    },
    queryCompany(){
      companyList().then((res)=>{
        if(res.success){
          this.companyArray = res.data;
        }
      })
    },
    queryProject(){
      projectList().then((res)=>{
        if(res.success){
          this.projectArray = res.data;
        }
      })
    },
    queryType(){
      typeList().then((res)=>{
        if(res.success){
          this.typeArray = res.data;
        }
      })
    },
    handleAvatarSuccess(res, file) {
      console.log("文件上传成功！")

      if(res.success){
        this.fileArray.push(res.data)
      }
    },
    handleRemove(file, fileList){
      var path = file.response.data;
      var index = this.fileArray.indexOf(path)
      this.fileArray.splice(index ,1)
    },
    submitOrderDetail(){
      this.tempOrderDetail.goodsId = this.goodsValue[2]
      this.orderDetailData.push(this.tempOrderDetail)
      this.orderDetailVisible = false
      this.tempOrderDetail = {}
      this.goodsValue = []
    },
    removeOrderDetail(row){
      var index = this.orderDetailData.indexOf(row)
      this.orderDetailData.splice(index, 1)
    },
    submitForm(status){
      this.form.order.status = status

      this.form.orderDetailList = this.orderDetailData

      if(this.fileArray.length>0){
        var filePath = "";
        for(var i in this.fileArray){
          var path = this.fileArray[i]
          filePath += ","+path
        }
        filePath = filePath.substring(1)
        this.form.order.filePath = filePath
      }

      submitForm(this.form).then((res)=>{
        if(res.success){
          this.form = {
            order:{
              filePath:''
            },
            orderDetailList:[]
          }
          this.orderDetailData = []
          this.$message.success("采购单提交成功")
          this.orderDialog = false

          this.query()
        }else{
          this.$message.error(res.msg)
        }
      })

    },
    query(){
      list().then((res)=>{
        if(res.success){
          this.tableData = res.data.list
          this.dept = res.data.dept
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    logout(){
      sessionStorage.removeItem("token");
      this.$router.push("/")
    },
    doSubmitApprove(id){
      submitApprove(id).then((res)=>{
        if(res.success){
          this.$message.success("提交成功")
          this.query()
        }
      })
    },
    edit(id){
      edit(id).then((res)=>{
        if(res.success){
          this.form = res.data
          this.username = res.data.order.username

          this.orderDetailData = res.data.orderDetailList

          this.orderDialog = true
        }
      })
    },
    approve(status){
      var id = this.form.order.id
      approve(id, status).then((res)=>{
        if(res.success){
          this.$message.success("审批完成！")

          this.form = {
            order:{
              filePath:''
            },
            orderDetailList:[]
          }
          this.orderDetailData = []
          this.orderDialog = false
          this.query()
        }
      })
    }
  },
  created() {
    this.query();

    this.queryGoods();
    this.queryType();
    this.queryProject();
    this.queryCompany();

    this.token = sessionStorage.getItem("token");
  }
}
</script>

<style scoped>

</style>